#include "client.h"

/* 计算文件的 SHA-1 哈希值，结果存入 sha1str（需至少 41 字节） */
int sha1_file(const char *filename, char *sha1str) {
    EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
    if (!mdctx) {
        fprintf(stderr, "Error: EVP_MD_CTX_new failed\n");
        return 0;
    }

    // 初始化 SHA-1 哈希计算
    if (EVP_DigestInit_ex(mdctx, EVP_sha1(), NULL) != 1) {
        fprintf(stderr, "Error: EVP_DigestInit_ex failed\n");
        EVP_MD_CTX_free(mdctx);
        return 0;
    }

    int fd = open(filename, O_RDONLY);
    if (fd == -1) {
        perror("open");
        EVP_MD_CTX_free(mdctx);
        return 0;
    }

    unsigned char buf[4096];
    while (1) {
        ssize_t sret = read(fd, buf, sizeof(buf));
        if (sret == -1) {
            perror("read");
            close(fd);
            EVP_MD_CTX_free(mdctx);
            return 0;
        }
        if (sret == 0) break;  // 文件读取完毕

        // 更新哈希计算
        if (EVP_DigestUpdate(mdctx, buf, sret) != 1) {
            fprintf(stderr, "Error: EVP_DigestUpdate failed\n");
            close(fd);
            EVP_MD_CTX_free(mdctx);
            return 0;
        }
    }
    close(fd);

    unsigned char md[EVP_MAX_MD_SIZE];
    unsigned int md_len;
    if (EVP_DigestFinal_ex(mdctx, md, &md_len) != 1) {
        fprintf(stderr, "Error: EVP_DigestFinal_ex failed\n");
        EVP_MD_CTX_free(mdctx);
        return 0;
    }
    EVP_MD_CTX_free(mdctx);

    // 将二进制哈希值转换为十六进制字符串
    for (unsigned int i = 0; i < md_len; ++i) {
        sprintf(sha1str + i * 2, "%02x", md[i]);
    }
    sha1str[md_len * 2] = '\0';  // 确保字符串以 '\0' 结尾

    return 1;
}


